import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { EXPERIMENT_STATE } from '../../constants';

export interface Experiment {
  name: string;
  state: string;
  trials: any[];
  [key: string]: any;
}

export interface ExperimentsState {
  experiments: Experiment[];
  inDesign: Experiment | null;
  openLaunchDialog: boolean;
}

const initialState: ExperimentsState = {
  experiments: [],
  inDesign: null,
  openLaunchDialog: false,
};

const experimentsSlice = createSlice({
  name: 'experiments',
  initialState,
  reducers: {
    setExperiments: (state, action: PayloadAction<Experiment[]>) => {
      state.experiments = action.payload;
      state.inDesign = action.payload.find((el) => el.state === EXPERIMENT_STATE.DESIGN) || null;
    },
    openLaunchDialog: (state) => {
      state.openLaunchDialog = true;
    },
    closeLaunchDialog: (state) => {
      state.openLaunchDialog = false;
    },
    addExperiment: (state, action: PayloadAction<Experiment>) => {
      state.experiments.push(action.payload);
    },
    removeExperiment: (state, action: PayloadAction<string>) => {
      state.experiments = state.experiments.filter((exp) => exp.name !== action.payload);
    },
    editExperiment: (state, action: PayloadAction<{ name: string; details: any }>) => {
      const index = state.experiments.findIndex((exp) => exp.name === action.payload.name);
      if (index !== -1) {
        state.experiments[index] = { ...state.experiments[index], ...action.payload.details };
      }
    },
    cloneExperiment: (state, action: PayloadAction<string>) => {
      const experiment = state.experiments.find((exp) => exp.name === action.payload);
      if (experiment) {
        const cloned = {
          ...experiment,
          name: `${experiment.name}_copy`,
          state: EXPERIMENT_STATE.DESIGN,
        };
        state.experiments.push(cloned);
      }
    },
  },
});

export const {
  setExperiments,
  openLaunchDialog,
  closeLaunchDialog,
  addExperiment,
  removeExperiment,
  editExperiment,
  cloneExperiment,
} = experimentsSlice.actions;

// Action creators for experiment viewing (these trigger Python calls via middleware/API)
export const viewExperimentResults = (payload: { name: string; trial: any }) => ({
  type: 'VIEW_EXPERIMENT_RESULTS',
  payload,
});

export const loadTrialModelSpec = (payload: {
  name: string;
  trial: any;
  onlyModelSpecification?: boolean;
}) => ({
  type: 'TRIAL_LOAD_MODEL_SPEC',
  payload,
});

export default experimentsSlice.reducer;

